var express = require('express');
var path = require('path');
var fs = require('fs');
var morgan = require('morgan'); // logger
var bodyParser = require('body-parser');
var _ = require('lodash');
var program = require('commander');
var util = require('util');

var dir = process.cwd();

var app = express();
app.set('port', (process.env.PORT || 3000));

app.use('/', express.static(__dirname + '/../../dist'));
app.use('/', express.static(__dirname + '/../public'));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use(morgan('dev'));

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test');
var db = mongoose.connection;
mongoose.Promise = global.Promise;

// Models
var Cat = require('./cat.model.js');

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log('Connected to MongoDB');

  // Files Browse APIs
  app.get('/files', function(req, res) {
    var currentDir = dir;
    var query = req.query.path || '';
    if (query) currentDir = path.join(dir, query);
    console.log("browsing ", currentDir);
    fs.readdir(currentDir, function(err, files) {
      if (err) {
        throw err;
      }
      var data = [];
      files.forEach(function (file) {
        try {
          var stats = fs.statSync(path.join(currentDir, file));
          var isDirectory = stats.isDirectory(); //statSync为同步stat(), 返回fs.Stats的实例；
          if (isDirectory) {
            data.push({name: file, isDirectory: true, path: path.join(query, file)});
          } else {
            var ext = path.extname(file);
            if (program.exclude && _.contains(program.exclude, ext)) {
              console.log("excluding file ", file);
              return;
            }
            data.push({name: file, ext: ext, isDirectory: false, path: path.join(query, file), info: stats});
          }
        } catch(e) {
          console.log(e);
        }
      });
      data = _.sortBy(data, function(f) { return f.name; });
      res.json(data);
    });

  });

  // Database APIs
  // select all
  app.get('/cats', function(req, res) {
    Cat.find({}, function(err, docs) {
      if(err) return console.error(err);
      res.json(docs);
    });
  });

  // count all
  app.get('/cats/count', function(req, res) {
    Cat.count(function(err, count) {
      if(err) return console.error(err);
      res.json(count);
    });
  });

  // create
  app.post('/cat', function(req, res) {
    var obj = new Cat(req.body);
    obj.save(function(err, obj) {
      if(err) return console.error(err);
      res.status(200).json(obj);
    });
  });

  // find by id
  app.get('/cat/:id', function(req, res) {
    Cat.findOne({_id: req.params.id}, function(err, obj) {
      if(err) return console.error(err);
      res.json(obj);
    })
  });

  // update by id
  app.put('/cat/:id', function(req, res) {
    Cat.findOneAndUpdate({_id: req.params.id}, req.body, function(err) {
      if(err) return console.error(err);
      res.sendStatus(200);
    })
  });

  // delete by id
  app.delete('/cat/:id', function(req, res) {
    Cat.findOneAndRemove({_id: req.params.id}, function(err) {
      if(err) return console.error(err);
      res.sendStatus(200);
    });
  });


  // all other routes are handled by Angular
  app.get('/*', function(req, res) {
    res.sendFile(path.join(__dirname,'/../../dist/index.html'));
  });

  app.listen(app.get('port'), function() {
    console.log('Server listening on port '+app.get('port'));
  });
});

module.exports = app;
